package com.xueyi.aixihu.entity.vo;

import com.alibaba.fastjson.JSON;
import com.xueyi.aixihu.config.SpringContextConfig;
import com.xueyi.aixihu.constant.AddressConstant;
import com.xueyi.aixihu.constant.OneLevelAuditConstant;
import com.xueyi.aixihu.constant.SystemRoleConstant;
import com.xueyi.aixihu.constant.TwoLevelAuditConstant;
import com.xueyi.aixihu.entity.po.DtNewsSort;
import com.xueyi.aixihu.entity.po.DtUsers;
import com.xueyi.aixihu.exception.SzException;
import com.xueyi.aixihu.interceptors.RequestInterceptor;
import com.xueyi.aixihu.mapper.MenuMapper;
import com.xueyi.aixihu.status.FinanceStatus;
import com.xueyi.aixihu.status.SystemCode;
import com.xueyi.aixihu.utils.FinalUtil;
import com.xueyi.aixihu.utils.JedisUtil;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 描述 Member成员类
 *
 * @auther 俞烨
 * @date 2022-08-13 14
 */
@Data
public class DtUsersVo extends DtUsers {

    /**
     * 查看SystemRoleConstant类
     */
    @Deprecated
    public static final List<Integer> roleIdList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
    private List<String> roleList;

    /**
     * 删除当前被禁用被删除用户的token信息
     */
    public static void deleteTokenDetail(Integer userId) {

        if (userId == null) return;
        Jedis jedis = JedisUtil.getJedis();
        try {
            Map<String, String> tokenMap = jedis.hgetAll("ALL_TOKEN:" + userId.toString());
            if (!CollectionUtils.isEmpty(tokenMap)) {
                tokenMap.forEach((key, value) -> {
                    jedis.del(key);
                });
            }
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }
    }

    /**
     * 获取当前登陆的用户
     *
     * @return
     */
    public static DtUsersVo findCurrentUser() {

        return RequestInterceptor.dtUsersLocal.get() == null ? initFalseStatus() : RequestInterceptor.dtUsersLocal.get();
    }

    private static DtUsersVo initFalseStatus() {

        DtUsersVo dtUsersVo = new DtUsersVo();
        dtUsersVo.setId(-10086);
        return dtUsersVo;
    }


    public String findUserManageAllAddressId() {

        StringJoiner joiner = new StringJoiner(",");

        String manageAreaIds = processAddressArr(findUserManageArea());
        if (StringUtils.hasLength(manageAreaIds)) {
            joiner.add(manageAreaIds);
        }

        String userManageCommunityId = findUserManageCommunityId();
        if (StringUtils.hasLength(userManageCommunityId)) {
            joiner.add(userManageCommunityId);
        }

        String userManageTownId = findUserManageTownId();
        if (StringUtils.hasLength(userManageTownId)) {
            joiner.add(userManageTownId);
        }

        String userManageJuWeiId = findUserManageJuWeiId();
        if (StringUtils.hasLength(userManageJuWeiId)) {
            joiner.add(userManageJuWeiId);
        }


        return joiner.toString();
    }

    /**
     * 查询该用户村的Id
     *
     * @return
     */
    public String findUserManageAreaId() {
        return processAddressArr(findUserManageArea());
    }

    /**
     * 查询用户镇级的id
     *
     * @return
     */
    public String findUserManageTownId() {
        return processAddressArr(findUserManageTown());
    }


    /**
     * 查询用户社区的id
     *
     * @return
     */
    public String findUserManageCommunityId() {
        return processAddressArr(findUserManageCommunity());
    }


    /**
     * 查询用户居委的id
     *
     * @return
     */
    public String findUserManageJuWeiId() {
        return processAddressArr(findUserManageJuWei());
    }

    /**
     * 处理集合的Arr返回 ， 拼接的字符串
     *
     * @param userManageArea
     * @return
     */
    private String processAddressArr(List<DtNewsSort> userManageArea) {

        if (!CollectionUtils.isEmpty(userManageArea)) {
            StringJoiner joiner = new StringJoiner(",");
            for (DtNewsSort sort : userManageArea) {
                joiner.add(sort.getId().toString());
            }
            return joiner.toString();
        }
        return "-111";
    }

    /**
     * 查询该用户管理的小区集合
     *
     * @return
     */
    public List<DtNewsSort> findUserManageArea() {
        return SpringContextConfig.getBean(MenuMapper.class).findUserManageArea(getId(), AddressConstant.CUN);
    }

    /**
     * 查询用户管理镇级
     *
     * @return
     */
    public List<DtNewsSort> findUserManageTown() {
        return SpringContextConfig.getBean(MenuMapper.class).findUserManageArea(getId(), AddressConstant.ZJ);
    }

    /**
     * 查询管理的社区集合
     *
     * @return
     */
    public List<DtNewsSort> findUserManageCommunity() {
        return SpringContextConfig.getBean(MenuMapper.class).findUserManageArea(getId(), AddressConstant.SQ);
    }

    /**
     * 查询管理的居委集合
     * @return
     */
    public List<DtNewsSort> findUserManageJuWei() {
        return SpringContextConfig.getBean(MenuMapper.class).findUserManageArea(getId(), AddressConstant.JW);
    }


    /**
     * 获取当前用户看到财务的状态是什么样子的
     *
     * @param statusType 1、代办    2、驳回    3、其他
     * @return
     */
    public String findUserFinanceLookCurrentStatus(Integer statusType) {
        Integer userMaxRole = findUserMaxRole();
        if (userMaxRole.equals(roleIdList.get(0)) || userMaxRole.equals(roleIdList.get(1))) {
            return "-10086";
        } else if (userMaxRole.equals(roleIdList.get(2)) || userMaxRole.equals(roleIdList.get(3))) {
            // 如果是代理会计或者是报账员，那么驳回他只能看见 -3 ， 代办只能看见 1 ， 其他什么都看不见
            return statusType.equals(1) ? FinanceStatus.ONE_AUDIT.type + "" : statusType.equals(2) ? FinanceStatus.TURN_ONE.type + "" : "-10086";
        } else if (userMaxRole.equals(roleIdList.get(4)) || userMaxRole.equals(roleIdList.get(5))) {
            //  * 5、经发办主任
            //  * 6、财务办主任
            // 代办和驳回只能看到自己的，但是其他能够看到代理会计或者是报账员的信息
            return statusType.equals(1) ? FinanceStatus.TWO_AUDIT.type + "" :
                    statusType.equals(2) ? FinanceStatus.TURN_TWO.type + "" :
                            FinanceStatus.ONE_AUDIT.type + "," + FinanceStatus.TURN_ONE.type + "," + FinanceStatus.TURN_ZERO.type;
        } else if (userMaxRole.equals(roleIdList.get(6))) {
            // 分管领导可以看到，自己的代办，没有驳回，但是能看到其他（代理会计或者是报账员的信息）、（经发办主任he 财务办主任)的其他信息
            return statusType.equals(1) ? FinanceStatus.THREE_AUDIT.type + "" :
                    statusType.equals(2) ? "-10086" :
                            FinanceStatus.ONE_AUDIT.type + "," + FinanceStatus.TWO_AUDIT.type + "," + FinanceStatus.TURN_ONE.type + ","
                                    + FinanceStatus.TURN_TWO.type + "," + FinanceStatus.TURN_ZERO.type;
        } else {
            return statusType.equals(1) ? (FinanceStatus.ONE_AUDIT.type + "," + FinanceStatus.TWO_AUDIT.type + "," + FinanceStatus.THREE_AUDIT.type)
                    : statusType.equals(2) ? (FinanceStatus.TURN_TWO.type + "," + FinanceStatus.TURN_ONE.type + "," + FinanceStatus.TURN_ZERO.type) :
                    "-10086";
        }
    }


    public Integer getUserMaxRole() {

        return findUserMaxRole();
    }

    /**
     * 查询当前用户审核报表可见的状态
     *
     * @param userMaxRole
     * @return
     */
    public List<Integer> findUserAuditFinanceStatus(Integer userMaxRole, Integer pageType) throws SzException {
        userMaxRole = userMaxRole == null ? findUserMaxRole() : userMaxRole;
        if (userMaxRole.equals(SystemRoleConstant.Z_CZS_SZ)) {
            if (pageType == null) {
                return Arrays.asList(OneLevelAuditConstant.SUBMIT_AUDIT, TwoLevelAuditConstant.ONE_CONSENT);
            } else {
                if (pageType == 1) {
                    return Collections.singletonList(OneLevelAuditConstant.SUBMIT_AUDIT);
                } else {
                    return Collections.singletonList(TwoLevelAuditConstant.ONE_CONSENT);
                }
            }
        } else if (userMaxRole.equals(SystemRoleConstant.Z_JGZ_CY) || userMaxRole.equals(SystemRoleConstant.Z_CZS_CY)) {
            return Arrays.asList(TwoLevelAuditConstant.SUBMIT_AUDIT,
                    TwoLevelAuditConstant.TWO_FAIL);
        } else if (userMaxRole.equals(SystemRoleConstant.Z_JGZ_ZZ)) {
            return Collections.singletonList(TwoLevelAuditConstant.ONE_CONSENT);
        } else {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "当前您的角色并不能进行审核操作");
        }
    }

    public String findUserAuditFinanceStatusStr(Integer userMaxRole, Integer pageType) throws SzException {
        List<Integer> userAuditFinanceStatus = findUserAuditFinanceStatus(userMaxRole, pageType);
        StringJoiner stringJoiner = new StringJoiner(",");
        if (!CollectionUtils.isEmpty(userAuditFinanceStatus)) {
            for (Integer auditFinanceStatus : userAuditFinanceStatus) {
                stringJoiner.add(auditFinanceStatus.toString());
            }
        }

        return stringJoiner.toString();
    }

    /**
     * 获取用户最大的角色id
     *
     * @return
     */
    public Integer findUserMaxRole() {

        Integer currentRoleId = 0;
        if (!CollectionUtils.isEmpty(getRoleList())) {
            currentRoleId = Integer.parseInt(getRoleList().get(0));
        }
        return currentRoleId;
    }

    /**
     * 校验当前登陆的用户是否有访问的权限
     *
     * @return
     */
    public Boolean validateRule(HttpServletRequest request) throws SzException {

        // 获取请求路径 /backend/xxxxx
        String requestURI = request.getRequestURI();
        if (RequestInterceptor.excludeRuleList.contains(requestURI)) {
            return true;
        }

        Jedis jedis = JedisUtil.getJedis();
        try {
            // 获取请求路径对应的id
            String ruleId = jedis.hget("ALL_RULE", requestURI);

            if (!StringUtils.hasLength(ruleId)) {
                return true;
            }
            // 遍历用户的角色，通过用户角色取出角色包含的权限集合
            if (!CollectionUtils.isEmpty(roleList)) {
                boolean userIsOwnRule = false;
                for (String roleId : roleList) {
                    // 用户有什么角色
                    // 角色有什么权限
                    // 当前用户的角色是否有访问当前路径的权限
                    String roleJson = jedis.hget("ROLE_ALL_CDZ", "ROLE:ID_CDZ" + roleId);
                    if (StringUtils.isEmpty(roleJson)) {
                        continue;
                    }

                    // 转换成对象
                    DtAuthGroupVo dtAuthGroupVo = JSON.parseObject(roleJson, DtAuthGroupVo.class);
                    if (dtAuthGroupVo.getRulesId().contains(ruleId)) {
                        userIsOwnRule = true;
                        break;
                    }
                }

                if (!userIsOwnRule) throw new SzException(SystemCode.USER_JURISDICTION_ERROR, "用户权限不足");
                return true;
            } else {
                throw new SzException(SystemCode.USER_JURISDICTION_ERROR, "用户权限不足");
            }
        } finally {

            FinalUtil.unLockAndCloseRedis(jedis);
        }
    }
    public  List<DtNewsSort> findSortParent(Integer userMaxRole,boolean isFlag){
        if (userMaxRole.equals(SystemRoleConstant.CUN) ||(userMaxRole.equals(SystemRoleConstant.Z_JGZ_CY) || userMaxRole.equals(SystemRoleConstant.Z_JGZ_ZZ))&&isFlag) {
            return Collections.singletonList(
                    new DtNewsSort(AddressConstant.CUN, null,
                            "村",
                            null,
                            null, null, null)
            );
        } else if (userMaxRole.equals(SystemRoleConstant.SQ)) {
            return Collections.singletonList(
                    new DtNewsSort(AddressConstant.SQ, null,
                            "社区",
                            null,
                            null, null, null)
            );
        } else if (
                userMaxRole.equals(SystemRoleConstant.Z_DJB_CY) || userMaxRole.equals(SystemRoleConstant.Z_DJB_ZR) ||
                userMaxRole.equals(SystemRoleConstant.Z_JGZ_CY) || userMaxRole.equals(SystemRoleConstant.Z_JGZ_ZZ)||
                SystemRoleConstant.Z_MZB_CY.equals(userMaxRole)||
                SystemRoleConstant.Z_NF_A_ZB_CY.equals(userMaxRole)||
                SystemRoleConstant.Z_GG_ZY_JY_ZX_CY.equals(userMaxRole)||
                SystemRoleConstant.Z_ZS_XM_B_CY.equals(userMaxRole)||
                SystemRoleConstant.Z_NY_FW_ZX_CY.equals(userMaxRole)||
                SystemRoleConstant.Z_LB_S_CY.equals(userMaxRole)||

                SystemRoleConstant.Z_MZB_ZR.equals(userMaxRole)||
                SystemRoleConstant.Z_NF_A_ZB_ZR.equals(userMaxRole)||
                SystemRoleConstant.Z_GG_ZY_JY_ZX_ZR.equals(userMaxRole)||
                SystemRoleConstant.Z_ZS_XM_B_ZR.equals(userMaxRole)||
                SystemRoleConstant.Z_NY_FW_ZX_ZR.equals(userMaxRole)||
                SystemRoleConstant.Z_LB_S_ZR.equals(userMaxRole)

        ) {
            return Arrays.asList(
                    new DtNewsSort(AddressConstant.CUN, null,
                            "村",
                            null,
                            null, null, null),
                    new DtNewsSort(AddressConstant.SQ, null,
                            "社区",
                            null,
                            null, null, null),
                    new DtNewsSort(AddressConstant.ZJ, null,
                            "镇",
                            null,
                            null, null, null),
                    new DtNewsSort(AddressConstant.JW, null,
                            "居委",
                            null,
                            null, null, null)
            );
        } else if (userMaxRole.equals(SystemRoleConstant.Z_CZS_CY) || userMaxRole.equals(SystemRoleConstant.Z_CZS_SZ)) {
            return Arrays.asList(
                    new DtNewsSort(AddressConstant.SQ, null,
                            "社区",
                            null,
                            null, null, null),
                    new DtNewsSort(AddressConstant.ZJ, null,
                            "镇",
                            null,
                            null, null, null),
                    new DtNewsSort(AddressConstant.JW, null,
                            "居委",
                            null,
                            null, null, null)
            );
        } else if (userMaxRole.equals(SystemRoleConstant.JU_WEI)) {
            return Collections.singletonList(
                    new DtNewsSort(AddressConstant.JW, null,
                            "居委",
                            null,
                            null, null, null)
            );
        } else {
            return new ArrayList<>();
        }
    }

    public List<DtNewsSort> findSortParent() {
        Integer userMaxRole = getUserMaxRole();
        return findSortParent(userMaxRole,true);
    }
}
